package com.imonsoft.sqm.validator.business.supplier_quality;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import com.imonsoft.sqm.pojo.business.supplier_quality.AnswerProblem;
import com.imonsoft.sqm.service.MessageUtil;
import com.imonsoft.sqm.service.business.supplier_quality.AnswerProblemService;

@Component("answerProblemValidator")
public class AnswerProblemValidator implements Validator {

	@Autowired
	private AnswerProblemService answerProblemService;

	@Override
	public boolean supports(Class<?> clazz) {
		return AnswerProblem.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {

	}

	public void methodAddValidate(Object target, Errors errors) {
		validate(target, errors);
		AnswerProblem answerProblem = (AnswerProblem) target;
		List<AnswerProblem> list =answerProblemService.findList(answerProblem);
		if (list.size() > 0) {
			errors.rejectValue("supplierCode", "message.unique.answerProblem.code", new Object[] {answerProblem.getSupplierCode(),answerProblem.getYear() }, "保存的供应商能有相同记录！");
		}
	}


	@Autowired
	private MessageUtil messageUtil;

	public List<String> getErrors(BindingResult result) {
		List<String> errors = new ArrayList<String>();
		for (ObjectError error : result.getAllErrors()) {
			errors.add(messageUtil.getMessage(error.getCode(), error.getArguments(), error.getDefaultMessage()));
		}
		return errors;
	}
}
